import Ajax from 'axios'
import qs from 'qs'
import setting from '@/config'
import { getToken, removeToken } from '@/util/auth'

const ajax = Ajax.create()
ajax.interceptors.request.use(function(config) {
    config.headers.Authorization = 'Bearer ' + getToken()
    if (process.env.NODE_ENV === 'development') {
        console.log('Bearer ' + getToken())
    }
    return config
})
ajax.interceptors.response.use(function(response) {
    return response
}, function(error) {
    if (process.env.NODE_ENV === 'development') console.log(error)
    if (error.response.data.message === 'Unauthenticated.' || error.response.data.message === 'WechatError') {
        removeToken()
        window.location.reload()
    }
    return Promise.reject(error.response)
})

/**
 * post请求
 * @param action
 * @param param
 * @method post OR get
 * @returns {Promise<AxiosResponse<T>>}
 */
export const sendPost = function(action, param) {
    let url = process.env.NODE_ENV === 'production' ? setting.requestUrl.pro : setting.requestUrl.dev
    url += action
    return ajax.post(url, qs.stringify(param))
}

/**
 * get 请求
 * @param action
 * @param param
 * @returns {Promise<AxiosResponse<T>>}
 */
export const sendGet = function(action, param) {
    let url = process.env.NODE_ENV === 'production' ? setting.requestUrl.pro : setting.requestUrl.dev
    url += action
    if(param) {
        url += '?' + qs.stringify(param);
    }
    return ajax.get(url)
}

/**
 * PUT请求
 * @param action
 * @param param
 * @method post OR get
 * @returns {Promise<AxiosResponse<T>>}
 */
export const put = function(action, param) {
    let url = process.env.NODE_ENV === 'production' ? setting.requestUrl.pro : setting.requestUrl.dev
    url += action
    return ajax.put(url, qs.stringify(param))
}

/**
 * delete删除请求
 * @param action
 * @param param
 * @returns {AxiosPromise}
 */
export const del = function(action, param) {
    let url = process.env.NODE_ENV === 'production' ? setting.requestUrl.pro : setting.requestUrl.dev
    url += action
    return ajax.delete(url, qs.stringify(param))
}

export const sendUpload = function(action, data, uploading) {
    const url = process.env.NODE_ENV === 'production' ? setting.requestUrl.pro : setting.requestUrl.dev
    return ajax.post(
        url + action,
        data,
        {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: (progress) => {
                uploading && uploading({ total: progress.total, loaded: progress.loaded })
            }
        }
    )
}

/**
 * 上传文件所需参数
 * @returns {{headers: {Authorization: string}, url: string}}
 */
export const uploadParams = function(action) {
    return {
        url: process.env.NODE_ENV === 'production' ? setting.requestUrl.pro + action : setting.requestUrl.dev + action,
        headers: {
            'Authorization': 'Bearer ' + getToken()
        }
    }
}

/**
 * 请求返回的错误处理
 * @param error
 */
export const handleError = function(error, vue) {
    const { message, errors } = error.data
    if (errors) {
        for (const attr in errors) {
            vue.$createToast({
                type: 'error',
                time: 2000,
                txt: errors[attr][0],
                zIndex: 3000
            }).show()
            return
        }
    } else if (message) {
        vue.$createToast({
            type: 'error',
            time: 2000,
            txt: message,
            zIndex: 3000
        }).show()
    } else {
        vue.$createToast({
            type: 'error',
            time: 2000,
            txt: error.data,
            zIndex: 3000
        }).show()
    }
}

export default { sendPost, sendGet }
